package com.bingxue.edu.common.job;

import com.bingxue.edu.common.enums.LessonStatusEnum;
import com.bingxue.edu.framework.job.DynamicJob;
import com.bingxue.edu.management.education.model.entity.Lesson;
import com.bingxue.edu.management.education.service.LessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.time.LocalDate;
import java.util.List;

import static com.bingxue.edu.management.education.model.entity.table.LessonTableDef.LESSON;

/**
 * 每小时执行一次
 * @author panbo
 * @since 2024/12/23
 */
@Slf4j
@DisallowConcurrentExecution
@RequiredArgsConstructor
@DynamicJob(name="课次状态更新任务", cron = "0 0 * * * ? ")
public class LessonStatusUpdateJob extends QuartzJobBean {

    private final LessonService lessonService;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        log.info("课次状态更新任务开始");
        List<Lesson> lessonList = lessonService.queryChain()
                .where(LESSON.LESSON_STATUS.eq(LessonStatusEnum.WAITING))
                .and(LESSON.END_TIME.lt(LocalDate.now()))
                .list();
        for (Lesson lesson : lessonList) {
            try {
                lessonService.completeLesson(lesson);
            } catch (Exception e) {
                log.warn("完成课次[{}]失败：{}", lesson, e.getMessage());
            }
        }
        log.info("课次状态更新任务结束");
    }
}
